package com.cml.rpc.server;

import com.cml.rpc.publicinterface.UserService;
import com.cml.rpc.publicpojo.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author cml
 * @create 2021/7/20 13:03
 * 服务端
 */
public class RpcServer {

    public static void main(String[] args) {
        UserService userService = new UserServiceImpl();
        try {
            ServerSocket serverSocket = new ServerSocket(7788);
            System.out.println("服务端启动成功...");
            while (true) {
                // 监听      accept是阻塞的
                Socket accept = serverSocket.accept();
                // 开启一个线程处理
                new Thread(() -> {
                    ObjectOutputStream oos = null;
                    ObjectInputStream ois = null;
                    try {
                        oos = new ObjectOutputStream(accept.getOutputStream());
                        ois = new ObjectInputStream(accept.getInputStream());
                        // 读取客户端传来的id
                        Integer id = ois.readInt();
                        System.out.println("接收到来自客户端的id = " + id);
                        // 调用服务端user实现类
                        User user = (User) userService.getUserById(id);
                        // 将结果user写入客户端
                        oos.writeObject(user);
                        oos.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                        System.out.println("从io中读取数据失败");
                    } finally {
                        try {
                            ois.close();
                            oos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("服务端启动失败");
        }
    }
}
